package fr.unice.polytech.chord.core.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import fr.unice.polytech.chord.core.Key;

/**
 * Utility class used for hash functions.
 * 
 * @author Anthony Parisy
 * @author Laurent Pellegrino
 * @author Marc Valdener
 * 
 * @version 10/28/2009
 */
public class HashUtil {

	/**
	 * Calculates the hash of a specified {@link Key}.
	 * 
	 * @param key
	 *            the key to hash.
	 * @return an array of bytes which the hash of the specified key.
	 */
	public static byte[] getSHA1(String key) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return md.digest(key.getBytes());
	}

	/**
	 * Calculates the hash of a specified key as String to a given modulo.
	 * 
	 * @param key
	 *            the key to use.
	 * @param modulo
	 *            the modulo to use.
	 * @return a {@link BigInteger} which the associated hash to a given key and
	 *         modulo.
	 */
	public static BigInteger getSHA1KeyRestrictedToIntervalByModulo(String key,
			int modulo) {
		BigInteger hashedKey = new BigInteger(HashUtil.getSHA1(key)).abs();
		BigInteger mod = new BigInteger(Integer.toString(modulo));
		return hashedKey.mod(mod);
	}

}
